<template>
  <div class="tree-container">
    <tree-node
      v-for="node in treeData"
      :key="node.id"
      :node="node"
      :field-names="fieldNames"
      :level="0"
      @node-click="handleNodeClick"
      @switch-lock="emit('switchLock', $event)"
      @node-drop="emit('node-drop', $event)"
      @update-text="emit('update-text', $event)"
    />
  </div>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, watch, ref, provide } from 'vue'
import TreeNode from './TreeNode.vue'

const props = defineProps({
  data: {
    type: Array,
    required: true
  },
  fieldNames: {
    type: String,
    default: 'label'
  },
  parentSelect: {
    type: Array<string>
  }
})

const emit = defineEmits([
  'node-click',
  'selection-change',
  'switchLock',
  'node-drop',
  'update-text'
])

// 处理数据，确保每个节点都有children字段
const treeData = ref<any[]>([])
watch(
  props.data,
  () => {
    treeData.value = props.data.map((node: any) => ({
      ...node,
      children: node.children || []
    }))
  },
  {
    deep: true
  }
)
watch(
  () => props.parentSelect,
  (newVal) => {
    selectedNodes.value = new Set(props.parentSelect)
  }
)

// 多选状态管理
const selectedNodes = ref<Set<string>>(new Set())
const lastSelectedNode = ref<string | null>(null)

// 提供状态给子组件
provide('selectedNodes', selectedNodes)

// 扁平化树结构（用于shift选择）
const flattenTree = (nodes: any[], result: any[] = []): any[] => {
  nodes.forEach((node) => {
    result.push(node)
    if (node.children && node.children.length) {
      flattenTree(node.children, result)
    }
  })
  return result
}

const handleNodeClick = (data: { node: any; event: MouseEvent }): void => {
  const nodeId = data.node.id
  const allNodes = flattenTree(treeData.value)

  // Shift选择逻辑
  if (data.event.shiftKey && lastSelectedNode.value) {
    const allIds = allNodes.map((n) => n.id)
    const lastIndex = allIds.indexOf(lastSelectedNode.value)
    const currentIndex = allIds.indexOf(nodeId)

    if (lastIndex !== -1 && currentIndex !== -1) {
      const start = Math.min(lastIndex, currentIndex)
      const end = Math.max(lastIndex, currentIndex)
      const newSelection = allIds.slice(start, end + 1)

      // 保留Ctrl选择项，只添加区间
      if (data.event.ctrlKey) {
        selectedNodes.value = new Set(newSelection)
      } else {
        newSelection.forEach((id) => selectedNodes.value.add(id))
      }
    }
  }
  // Ctrl选择逻辑
  else if (data.event.ctrlKey) {
    if (selectedNodes.value.has(nodeId)) {
      selectedNodes.value.delete(nodeId)
    } else {
      selectedNodes.value.add(nodeId)
    }
  }
  // 普通选择逻辑
  else {
    selectedNodes.value = new Set([nodeId])
  }

  // 更新最后选择的节点（Shift操作时不更新）
  lastSelectedNode.value = nodeId

  emit('node-click', data.node)
  emit('selection-change', Array.from(selectedNodes.value))
}

//强制更新数据
const forceUpdate = (newData) => {
  treeData.value = newData.map((node: any) => ({
    ...node,
    children: node.children || []
  }))
}
//清空选中
const clearSelection = () => {
  selectedNodes.value.clear()
}
//暴露出去
defineExpose({ forceUpdate, clearSelection })
</script>

<style scoped lang="scss">
/* 原有样式保持不变 */
</style>
